import React, { useState, useRef } from 'react';
import {
  TextField,
  Box,
  GridLegacy as Grid,
  InputAdornment,
  styled,
} from '@mui/material';
import { Folder as FolderIcon } from '@mui/icons-material';
import { useAppDispatch } from '../../../redux/hooks';
import ActionDialog from './ActionDialog';
import FileBrowser from '../../general/FileBrowser';
import NetPyNEField from '../../general/NetPyNEField';
import ListComponent from '../../general/List';
import Checkbox from '../../general/Checkbox';
import Tooltip from '../../general/Tooltip';

const StyledContainer = styled(Box)<{ component?: string }>(({ theme }) => ({
  marginTop: theme.spacing(2),
  display: 'flex',
  flexDirection: 'row',
  alignItems: 'flex-end',
  width: '103%',
  overflow: 'hidden',
}));

const StyledIcon = styled(Box)(({ theme }) => ({
  '&:hover': {
    backgroundColor: 'inherit',
  },
  flex: '0 0 4%',
  marginRight: theme.spacing(2),
  width: theme.typography.h3.fontSize,
  height: theme.typography.h3.fontSize,
  padding: '0px !important',
  zIndex: theme.zIndex.modal,
  cursor: 'pointer',
}));

interface ImportCellParamsDialogProps {
  open?: boolean;
  cellRuleName?: string;
  onRequestClose?: () => void;
  [key: string]: any;
}

/**
 * ImportCellParamsDialog Component
 * Dialog for importing cell template parameters from .py or .hoc files
 */
const ImportCellParamsDialog: React.FC<ImportCellParamsDialogProps> = ({
  open = false,
  cellRuleName = '',
  onRequestClose,
  ...otherProps
}) => {
  const dispatch = useAppDispatch();
  const [label, setLabel] = useState(cellRuleName);
  const [fileName, setFileName] = useState('');
  const [cellName, setCellName] = useState('');
  const [modFolder, setModFolder] = useState('');
  const [compileMod, setCompileMod] = useState(false);
  const [importSynMechs, setImportSynMechs] = useState(false);
  const [explorerDialogOpen, setExplorerDialogOpen] = useState(false);
  const [exploreOnlyDirs, setExploreOnlyDirs] = useState(false);
  const [explorerParameter, setExplorerParameter] = useState<string>('');

  const cellArgsRef = useRef<any>(null);

  const showExplorerDialog = (param: string, onlyDirs: boolean): void => {
    setExplorerDialogOpen(true);
    setExplorerParameter(param);
    setExploreOnlyDirs(onlyDirs);
  };

  const closeExplorerDialog = (fieldValue: any): void => {
    setExplorerDialogOpen(false);
    if (fieldValue) {
      switch (explorerParameter) {
        case 'fileName':
          setFileName(fieldValue.path);
          break;
        case 'modFolder':
          setModFolder(fieldValue.path);
          break;
        default:
          console.error('Not a valid parameter!');
      }
    }
  };

  const cellArgs = cellArgsRef.current?.state?.children || {};

  const command = 'netpyne_geppetto.importCellTemplate';
  const args = {
    cellArgs,
    fileName,
    cellName,
    label,
    modFolder,
    importSynMechs,
    compileMod,
  };

  return (
    <>
      <ActionDialog
        buttonLabel="Import"
        message="LOADING TEMPLATE"
        title="Import cell template (.py or .hoc)"
        command={command}
        args={args}
        open={open}
        onRequestClose={onRequestClose}
        {...otherProps}
      >
        <Box mb={1}>
          <TextField
            id="importCellParamsRuleLabel"
            variant="filled"
            value={label}
            fullWidth
            label="Cell rule label"
            onChange={(e) => setLabel(e.target.value)}
          />
        </Box>

        <NetPyNEField id="netParams.importCellParams.cellName" className="textField">
          <TextField
            id="importCellParamsCellName"
            variant="filled"
            fullWidth
            value={cellName}
            onChange={(e) => setCellName(e.target.value)}
          />
        </NetPyNEField>

        <NetPyNEField id="netParams.importCellParams.fileName">
          <TextField
            id="importCellParamsFileName"
            variant="filled"
            fullWidth
            value={fileName}
            onChange={(e) => setFileName(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Tooltip title="File explorer" placement="top">
                    <FolderIcon
                      onClick={() => showExplorerDialog('fileName', false)}
                      sx={{ cursor: 'pointer' }}
                    />
                  </Tooltip>
                </InputAdornment>
              ),
            }}
          />
        </NetPyNEField>

        <NetPyNEField id="netParams.importCellParams.modFolder">
          <TextField
            id="importCellParamsModFolder"
            fullWidth
            variant="filled"
            value={modFolder}
            onChange={(e) => setModFolder(e.target.value)}
            helperText="Important: if external mod files are required please select the mod folder path"
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Tooltip title="File explorer" placement="top">
                    <FolderIcon
                      onClick={() => showExplorerDialog('modFolder', true)}
                      sx={{ cursor: 'pointer' }}
                    />
                  </Tooltip>
                </InputAdornment>
              ),
            }}
          />
        </NetPyNEField>

        <ListComponent
          id="cellArgs"
          realType="dict"
          label="argument as key:value"
          floatingLabelText="Cell Template Parameters (key:value pair)"
          ref={cellArgsRef}
        />

        <Grid container spacing={1}>
          <Grid item>
            <NetPyNEField id="netParams.importCellParams.importSynMechs">
              <Checkbox
                fullWidth
                noBackground
                checked={importSynMechs}
                onChange={() => setImportSynMechs(!importSynMechs)}
              />
            </NetPyNEField>
          </Grid>
          <Grid item>
            <NetPyNEField id="netParams.importCellParams.compileMod">
              <Checkbox
                id="importCellParamsCompileMod"
                fullWidth
                noBackground
                checked={compileMod}
                onChange={() => setCompileMod(!compileMod)}
              />
            </NetPyNEField>
          </Grid>
        </Grid>
      </ActionDialog>

      <FileBrowser
        open={explorerDialogOpen}
        exploreOnlyDirs={exploreOnlyDirs}
        onRequestClose={closeExplorerDialog}
      />
    </>
  );
};

export default ImportCellParamsDialog;

